package emt.friendtracking.maps;

import android.app.Service;
import android.content.Intent;
import android.location.LocationManager;
import android.os.IBinder;
import android.util.Log;
import emt.friendtracking.BaseActivity;
import emt.friendtracking.MyApplication;
import emt.friendtracking.locationmodule.Coordinates;
import emt.friendtracking.locationmodule.CoordinatesHandler;
import emt.friendtracking.locationmodule.CoordinatesUpdateListener;
import emt.friendtracking.locationmodule.LocationIdentifier;
import emt.friendtracking.maps.org.ci.geo.route.Helper;
import emt.friendtracking.smsmodule.Message;

public class TimeToArrival extends Service implements CoordinatesUpdateListener
{
	private static final String TAG = TimeToArrival.class.getSimpleName();
	
	@Override
	public IBinder onBind(Intent arg0)
	{
		return null;
	}	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		Log.i(TAG, "onStart");
		
        //Location stuff
		if (BaseActivity.prefs.getBoolean("usegps", true))
		{
			@SuppressWarnings("static-access")
			LocationIdentifier identifier = LocationIdentifier.getInstance((LocationManager) 
					MyApplication.getAppContext().getSystemService(MyApplication.getAppContext().LOCATION_SERVICE));
			identifier.startLocationSearching();
	        CoordinatesHandler.getCoordinatesHandler().addCoordinatesListener(this);
		}
		return START_STICKY;
	}
	
	@Override
	public void onNewCoordinates(Coordinates coordinates)
	{
		float speed = coordinates.getSpeed();
		Log.i(TAG, "Accuracy: " + coordinates.getAccuracyString() + ". Speed: " + Float.toString(speed) +  ". Has speed: " + coordinates.hasSpeed());
		
		if (coordinates.getAccuracy() < BaseActivity.getAccuracy())
		{
			if (coordinates.hasSpeed())
			{
				CoordinatesHandler.getCoordinatesHandler().removeCoordinatesListener(this);

				double distanceInMeters = Helper.getDistance(coordinates.getLongitude(), coordinates.getLatitude(), TrackingActivity.information.getLongitudeOther(), TrackingActivity.information.getLatitudeOther());
				float speedMetersPerSecond = speed;
				int minutesToUse = (int) ((distanceInMeters / speedMetersPerSecond) / 60);
				
				String message;
				try
				{
					message = Message.make(BaseActivity.getUsername(), minutesToUse);
					BaseActivity.sms.sendASMS(TrackingActivity.information.getPhoneNumber(), message);
					stopService(new Intent(MyApplication.getAppContext(), TimeToArrival.class));
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}